<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <div style="transform: translateX(40px)">
          <h2>分类</h2>
          <h5>{{submitBtn}}</h5>
        </div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="别名">
            <el-input v-model="form.otherName"></el-input>
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入内容"
              v-model="form.describes"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="图片">
            <div class="upload-container avatar">
              <el-upload class="upload-demo avatar" action="" :on-preview="handlePreview" :on-remove="handleRemove" :limit="1"
                :file-list="fileList" :show-file-list="false"  :before-upload="BeforeUpload" :http-request="Upload" list-type="picture-card">
                <img v-if="form.imgclass" :src="form.imgclass" class="avatar">
              </el-upload>
            </div>
          </el-form-item>
          <el-form-item label="置顶分类">
            <el-switch  active-value="1" inactive-value="0" v-model="form.top"></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{submitBtn}}</el-button>
            <el-button @click="onCancle">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-table
          v-loading="listLoading"
          :data="list"
          :default-sort="{ prop: 'date', order: 'ascending' }"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column min-width="140px" label="名称">
            <template slot-scope="{ row }">
                <span>{{ row.name }}</span>
            </template>
          </el-table-column>

          <el-table-column width="120px" align="center" label="描述">
            <template slot-scope="scope">
              <span>{{ scope.row.describes }}</span>
            </template>
          </el-table-column>

          <el-table-column width="100px" label="别名">
            <template slot-scope="scope">
              <span>{{ scope.row.otherName }}</span>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="置顶">
            <template slot-scope="scope">
              <span v-if="scope.row.top === 1">是</span>
              <span v-else>否</span>
            </template>
          </el-table-column>
          <el-table-column width="100px"  label="图片">
            <template slot-scope="scope">
             <el-image
               style="width: 80; height: 80px"
               :src="scope.row.imgclass">
             </el-image>
            </template>
          </el-table-column>
          <el-table-column class-name="status-col" label="文章总数" width="110">
            <template slot-scope="{ row }">
              <el-tag style="display: flex;justify-content: center;" >{{ row.num }} </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateArtive(scope.row)">
                修改
              </el-button>
              <el-button
                style="margin-left: 10px"
                type="danger"
                size="mini"
                icon="el-icon-edit"
                @click="delectArtive(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { newResourceClass,updateResourceClass } from '@/api/resource'
import { allResourceClass } from '@/api/resource'
import { DeleteResourceClass } from '@/api/resource'
import { updateImage } from '@/api/updateImage'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'ArticleList',
  components: { Pagination },
  data() {
    return {
      list: null,
      fileList:[],
      updateForm:{},
      newFile: new FormData(), //   1. 定义一个newFile变量（FormData 对象）
      total: 0,
      listLoading: true,
      submitBtn:"添加分类",
      listQuery: {
        page: 1,
        limit: 8
      },
      form: {
        name: '',
        otherName: '',
        describes: '',
        imgclass: '',
        top: 0
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    //修改分类
    updateArtive(item){
        console.log(item);
        this.updateForm = item;
        this.form.name = item.name;
        this.form.otherName = item.otherName;
        this.form.describes = item.describes;
        this.form.imgclass = item.imgclass;
        this.form.top = item.top;
        this.submitBtn="修改分类";
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //  this.imageList.remove(file)
    },
    handlePreview(file) {
      console.log(file);
    },
    BeforeUpload(file) {
      if (file) {
        this.newFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。
        console.log(this.newFile.get('file'))
        console.log(this.newFile.get('file'), "123")
      } else {
        return false;
      }
    },
    Upload() {
      const newData = this.newFile.get('file'); //  3. 拿到刚刚的数据，并将其传给后台
      console.log(this.newFile)
      console.log(newData, "564")
      var that = this;
      var form2 = new FormData();
      form2.append('editormd-image-file', newData, newData.name)
      updateImage(form2).then(resp => {
        this.$message({
          message: '上传成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
        //上传一张后重置数据
        this.newFile = new FormData()
        var imgUrl = resp.data.url;//根据返回值得不同这里要自己定义
        this.tempUrl = imgUrl
        console.log("上传后的图片"+imgUrl)
        that.form.imgclass = imgUrl;
        console.log(that.form.imgclass)
        //  this.fileList.append('url',this.tempUrl);
        var aa = {
          "url": this.tempUrl,
          "name": this.tempUrl,
        }
        this.fileList.push(aa)
      }).catch((e) => {
        this.$message.error('抱歉,上传失败');
        this.theprogress = false
        console.log("上传失败")
      })

    },
    delectArtive(id) {
      this.$confirm('此操作将永久删除文章分类是否确认删除？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonClass: "danger",
        confirmButtonText: '删除',
        cancelButtonText: '放弃删除'
      }).then(() => {
          DeleteResourceClass(id).then(resp => {
            this.$notify({
              title: '成功',
              message: '您已成功删除该分类',
              type: 'success'
            });
            //刷新当前页面
           this.getList()
          })
        }).catch(action => {
          this.$message({
            type: 'info',
            message: action === 'cancel'
              ? '放弃删除'
              : '保留当前分类'
          })
        });
    },
    formatDate(time) {
      let data = new Date(time)
      return formatDate(data, 'yyyy-MM-dd hh:mm ')
    },
    getList() {
      this.listLoading = true
      allResourceClass(this.listQuery).then(resp => {
        this.list = resp.data.data
        this.total = resp.data.total
        this.listLoading = false
      })
    },
    onSubmit(){
      let that = this
      if(this.submitBtn === "修改分类")
      {
         console.log("修改分类updaSquareClass")
        that.updaSquareClass();
      }else
      {
         that.createSquareClass();
      }
    },
    //修改分类
    updaSquareClass(){
        let that = this
        this.loading = true
        this.updateForm.name = this.form.name;
        this.updateForm.otherName = this.form.otherName;
        this.updateForm.describes = this.form.describes;
        this.updateForm.imgclass = this.form.imgclass;
        this.updateForm.top = this.form.top;
        updateResourceClass(that.updateForm).then(resp => {
          //做一个简单的返回数据判断
          console.log(resp)
          if (resp.status === 200) {
            if(resp.data == 143){
              console.log("修改失败")
              this.loading = false
              this.$notify.error({
                title: '失败',
                message: '该分类修改失败',
              })
            }
            if(resp.data == 1){
              this.submitBtn = "创建分类"
              this.getList()
              this.$notify({
                title: '成功',
                message: '修改分类成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
            }
          } else {
            console.log("修改失败")
          }
        }).catch((e) => {
            console.log('error submit!!')
            this.loading = false
            this.$notify.error({
              title: '失败',
              message: '请检查网络连接',
            })
            return false
          })
    },
    //创建分类
    createSquareClass(){
        let that = this
        this.loading = true
        newResourceClass(that.form).then(resp => {
          //做一个简单的返回数据判断
          console.log(resp)
          if (resp.status === 200) {
            if(resp.data == 143){
              console.log("创建失败")
            this.loading = false
            this.$notify.error({
              title: '失败',
              message: '该分类已存在',
            })
            }
            if(resp.data == 1){
                        this.getList()
            this.$notify({
              title: '成功',
              message: '创建分类成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            }
          } else {
            console.log("创建失败")
          }
        }).catch((e) => {
            console.log('error submit!!')
            this.loading = false
            this.$notify.error({
              title: '失败',
              message: '请检查网络连接',
            })
            return false
          })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
    }
    .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }
</style>
